var ngModel = require( "mainModule" ).ng;
var cp = require( "mainModule" ).cp;
var version = require('versionNum').version;
var angular = require( 'angular' );

ngModel.component('test', {
    templateUrl: version + '_components/test/test.html',
    controller: ['$rootScope','$state','$timeout',
        function ($rootScope,$state,$timeout) {
	      
	      	var index = 0;
            this.add = function(){  
                // angular.element( document.getElementById("div1") ).append( require( "../dynamicload/dynamic.html" ) );  
                // registerController("div2", "div1_ctr2", ["$scope",function($scope){  
                //     $scope.hello = "world";
                // }]); 
                require.ensure([],function( require ){
                    var html = require( "../dynamicload/dynamic.html" )
                 	var ctrl = require( "../dynamicload/dynamic.js" )
                 	$rootScope.$evalAsync( function(){
                 		angular.element( document.getElementById("div1") ).append( 
                 			angular.element( html ).attr("id","div2"+index )[0]
                 		);  
                 		registerController("div2"+index, "div1_ctr2",ctrl);
                 	});
                 		
                	
                	// console.log( require( "../dynamicload/dynamic.js" ) );
                	// registerController("div2", "div1_ctr2",require( "../dynamicload/dynamic.js" )); 
                });
      			index++;
            }  
	         

	        function registerController(elementId, controllerName, func){  
	            angular.element( document.getElementById( elementId) ).attr("ng-controller",controllerName);
                cp.cp.register(controllerName, func); 
                angular.element( document.getElementById( elementId ) ).injector().invoke(function($compile, $rootScope) {  
                    $compile( document.getElementById(elementId) )($rootScope);  
                });
	        }

		}
	]
});